import React, { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from '../../../shared/state/auth.jsx';

const RequireAuth = ({ children }) => {
  const { isAuthenticated, openAuthModal } = useAuth();
  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    if (!isAuthenticated) {
      try {
        const target = `${location.pathname}${location.search}${location.hash}`;
        if (location.pathname !== '/') {
          sessionStorage.setItem('auth.redirectTo', target || '/');
          navigate('/', { replace: true });
        }
      } catch {}
      openAuthModal('login');
    }
  }, [isAuthenticated, location.pathname]);

  return children;
};

export default RequireAuth;
